/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { debounce } from 'lodash';
import { Modal, Row, Col, Form, Input, Button, message, Popconfirm, Icon } from 'antd';
import StandardTable from '@/components/StandardTable';
import styles from './style.less';
import UploadWithCrypto from '@/components/upload-width-crypto';

const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ loading, blacklist }) => ({
  blacklist,
  loading: loading.effects['blacklist/getBlack'],
  addBlack: loading.effects['blacklist/addBlack'],
  delBlack: loading.effects['blacklist/delBlack'],
}))
export default class Blacklist extends PureComponent {
  handleStandardTableChange = debounce(
    pagination => {
      const { dispatch } = this.props;
      this.current = pagination.current;
      const params = {
        page: pagination.current,
        phone: this.val,
      };
      dispatch({
        type: 'blacklist/getBlack',
        payload: params,
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  constructor(props) {
    super(props);
    this.excel = {
      name: 'blacklist',
      action: '/Api/YZ/CourierStation/importBlack',
      data: {
        data_type: 'file',
      },
      showUploadList: false,
    };
    this.current = 1;
  }

  state = {
    selectedRows: [],
    uploading: false,
  };

  componentDidMount = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'blacklist/getBlack',
      payload: {
        page: 1,
        phone: '',
      },
    });
    dispatch({
      type: 'blacklist/getSync',
    });
  };

  showConfirm = params => {
    confirm({
      centered: true,
      okText: '确定',
      cancelText: '取消',
      title: '温馨提示',
      ...params,
    });
  };

  // 批量删除
  handleBatchDelete = data => {
    const { dispatch } = this.props;
    let ids = [];
    data.forEach(v => {
      ids.push(v.id);
    });
    ids = ids.join(',');
    if (data == '') {
      message.error('请选择黑名单');
      return;
    }
    this.showConfirm({
      okText: '是',
      cancelText: '否',
      content: '是否删除黑名单',
      onOk: () => {
        dispatch({
          type: 'blacklist/delBlack',
          payload: {
            ids,
            phone: this.val,
            page: this.current,
          },
        });
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  // 添加黑名单
  addBlack = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'blacklist/save',
      payload: { formVisible: true },
    });
  };

  okChange = () => {
    const { dispatch, blacklist } = this.props;
    const { is_sync } = blacklist;
    dispatch({
      type: 'blacklist/setSync',
      payload: {
        is_sync: is_sync == 1 ? 0 : 1,
      },
    });
  };

  openOrClose = is_sync => (is_sync == 1 ? '关闭' : '开启');

  beforeUpload = file => {
    const fileArray = file.name.split('.');
    const fileType = fileArray[fileArray.length - 1];
    const isExcle = fileType === 'xlsx' || fileType === 'xls' || fileType === 'csv';

    if (!isExcle) {
      message.error('请选择 .xlsx .csv文件上传!');
      return false;
    }
    return true;
  };

  onChange = files => {
    const { dispatch } = this.props;
    const { status, response = {} } = files.file;
    const { code, msg } = response;
    this.setState({
      uploading: status === 'uploading',
    });
    if (code >= 0) {
      if (code == 0) {
        message.success('导入成功！');
        dispatch({
          type: 'blacklist/getBlack',
          payload: {
            page: 1,
          },
        });
        dispatch({
          type: 'blacklist/getSync',
        });
      } else {
        Modal.error({
          content: msg,
          okText: '知道了',
          cancelText: null,
        });
      }
    }
  };

  // 删除单条黑名单
  delBlack({ id }) {
    const { dispatch } = this.props;
    dispatch({
      type: 'blacklist/delBlack',
      payload: {
        ids: id,
        page: this.current,
        phone: this.val,
      },
    });
  }

  // 渲染添加黑名单表单
  renderModalForm() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
    };
    const AddForm = Form.create()(props => {
      const { form } = props;
      const { dispatch } = this.props;
      const { getFieldDecorator, validateFields } = form;
      // modal的确定按钮
      const modalSubmit = e => {
        e.preventDefault();
        validateFields((err, values) => {
          this.setState({
            phone: values.phone,
            remark: values.remark,
          });
          if (!err) {
            dispatch({
              type: 'blacklist/addBlack',
              payload: {
                ...values,
              },
            });
          }
        });
      };
      return (
        <div>
          <p className="title">添加黑名单</p>
          <div className="content">
            <div>
              <Form onSubmit={modalSubmit}>
                <FormItem {...formItemLayout} label="黑名单号码">
                  {getFieldDecorator('phone', {
                    initialValue: this.state.phone || '',
                    rules: [
                      { required: true, message: '手机号不能为空!' },
                      { pattern: /^1[3456789]{1}\d{9}$/, message: '请输入正确的手机号！' },
                    ],
                  })(<Input placeholder="请输入号码" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="添加原因">
                  {getFieldDecorator('remark', {
                    initialValue: this.state.remark || '',
                    rules: [{ required: false }],
                  })(<Input placeholder="请输入原因" />)}
                </FormItem>
                <FormItem>
                  <div className="submit">
                    <Button type="primary" htmlType="submit">
                      确定
                    </Button>
                    <Button
                      className="cancel"
                      onClick={() =>
                        dispatch({ type: 'blacklist/save', payload: { formVisible: false } })
                      }
                    >
                      取消
                    </Button>
                  </div>
                </FormItem>
              </Form>
            </div>
          </div>
        </div>
      );
    });
    return <AddForm />;
  }

  // 渲染查询表单
  renderSearchForm = () => {
    const SearchForm = Form.create()(props => {
      const { form } = props;
      const { dispatch, loading } = this.props;
      const { getFieldDecorator } = form;
      const handleSearch = debounce(
        e => {
          e.preventDefault();
          form.validateFields((err, fieldsValue) => {
            this.val = fieldsValue.phone;
            const values = {
              ...fieldsValue,
              page: 1,
            };
            dispatch({
              type: 'blacklist/getBlack',
              payload: values,
            });
          });
        },
        500,
        {
          leading: true,
          trailing: false,
        },
      );
      return (
        <Form onSubmit={handleSearch} layout="inline" style={{ textAlign: 'right' }}>
          <FormItem validateStatus="success">
            {getFieldDecorator('phone', {
              initialValue: this.val || '',
            })(<Input placeholder="请输入黑名单号码" />)}
          </FormItem>
          <FormItem style={{ margin: '0' }}>
            <span>
              <Button type="primary" htmlType="submit" key="search" icon="search" loading={loading}>
                查询
              </Button>
            </span>
          </FormItem>
        </Form>
      );
    });
    return <SearchForm />;
  };

  render() {
    const { selectedRows, uploading } = this.state;
    const { loading, blacklist, dispatch } = this.props;
    const { list, pagination, formVisible, openVisible, is_sync } = blacklist;
    const data = { list, pagination };
    const { total, current, pageSize } = pagination;
    const columns = [
      {
        title: '序号',
        render: (text, record, index) => total - pageSize * (current - 1) - index,
      },
      {
        title: '黑名单号码',
        dataIndex: 'phone',
      },
      {
        title: '添加原因',
        dataIndex: 'remark',
      },
      {
        title: '添加日期',
        dataIndex: 'create_at',
      },
      {
        title: '数据来源',
        dataIndex: 'source',
      },
      {
        title: '操作',
        render: record => (
          <Popconfirm
            placement="top"
            title="确定删除该黑名单？"
            onConfirm={() => this.delBlack(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="primary" size="small">
              删除
            </Button>
          </Popconfirm>
        ),
      },
    ];
    return (
      <>
        <div style={{ paddingBottom: '24px' }}>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={16} sm={24}>
              <Row type="flex" align="middle">
                <Col>
                  <Button type="primary" className={styles.mr_10} onClick={() => this.addBlack()}>
                    添加黑名单
                  </Button>
                </Col>
                <Col>
                  <UploadWithCrypto
                    {...this.excel}
                    onChange={this.onChange}
                    beforeUpload={this.beforeUpload}
                  >
                    <Button type="primary" className={styles.mr_10} loading={uploading}>
                      <Icon type="upload" /> 导入
                    </Button>
                  </UploadWithCrypto>
                </Col>
                <Col>
                  <Button
                    type="primary"
                    className={styles.mr_10}
                    href="https://upload.kuaidihelp.com/inn/excel/hmd.xlsx"
                  >
                    下载模板
                  </Button>
                </Col>
                {/* <Col>
                  <span className={styles.mr_10}>
                    同步全部下属驿站黑名单功能
                    {is_sync == 1 ? '已' : '未'}
                    开启
                  </span>
                  <a
                    onClick={() =>
                      dispatch({ type: 'blacklist/save', payload: { openVisible: true } })
                    }
                  >
                    {this.openOrClose(is_sync)}
                  </a>
                </Col> */}
              </Row>
            </Col>
            <Col md={8} sm={24}>
              {this.renderSearchForm()}
            </Col>
          </Row>
        </div>
        <StandardTable
          rowKey="id"
          loading={loading}
          data={data}
          columns={columns}
          selectedRows={selectedRows}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
        <div style={{ padding: '10px 30px' }}>
          <a onClick={() => this.handleBatchDelete(selectedRows)}>批量删除</a>
        </div>
        <Modal
          className={styles.blacklistModal}
          centered
          visible={formVisible}
          footer={null}
          destroyOnClose
          onCancel={() => dispatch({ type: 'blacklist/save', payload: { formVisible: false } })}
          afterClose={() => this.setState({ phone: '', remark: '' })}
        >
          {this.renderModalForm()}
        </Modal>
        <Modal
          destroyOnClose
          title={`${this.openOrClose(is_sync)}同步全部下属驿站黑名单功能`}
          visible={openVisible}
          onOk={this.okChange}
          okText={this.openOrClose(is_sync)}
          onCancel={() => dispatch({ type: 'blacklist/save', payload: { openVisible: false } })}
          cancelText="取消"
          centered
        >
          <p>
            {is_sync == 1
              ? '该功能关闭后，将不再同步下属驿站单独维护的黑名单'
              : '该功能开启后，将自动同步下属驿站单独维护的黑名单，每天零点至一点之间自动同步黑名单数据'}
          </p>
        </Modal>
      </>
    );
  }
}
